package com.medata.utils;

import com.medata.dataObject.Databaselist;
import com.medata.dataObject.Docobject;
import com.medata.exeptions.YunExceptions;
import com.medata.service.DatabaselistService;
import com.medata.service.DocobjectService;
import org.apache.commons.io.FileUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：zb
 * @date ：Created in 2019/5/6 0006 13:39
 * @description： 文件上传, 下载, 压缩, 解压
 */

public class FileUploadUtil {

    //上传
    public static String upload(MultipartFile file) {
        String path = System.getProperty("user.dir");
        path = path.replaceAll("\\\\", "\\/");
        path = path + "/src/main/resources/file/" + file.getOriginalFilename();
        File newfile = new File(path);
        try {
            file.transferTo(newfile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传成功";
    }

    //下载
    public static HttpServletResponse download(File file, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream;charset=UTF-8");
        String filename = file.getName();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        try {
            FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    //压缩
    public static String compressFiles(List<String> files, String zipFilePath) throws IOException {
        File file2 = null;
        Zip zip = new Zip();
        Project prj = new Project();
        FileSet fileSet = new FileSet();
        File zipfile=null;
        zip.setProject(prj);
        long sleepTime=1000;
        String uid=UidUtil.getUid();
        File demoFile=new File(zipFilePath);
        for (String filepath : files) {
            File file = new File(filepath);
            file2 = new File(demoFile.getParentFile() + "/"+uid);
            if (!file2.exists()) {
                file2.mkdirs();
            }
            sleepTime=sleepTime+(file.length()/50485);
            File file1 = new File(demoFile.getParentFile() + "/"+uid+"/" + file.getName());
            FileCopyUtils.copy(new FileInputStream(file), new FileOutputStream(file1));
            zipfile = new File(zipFilePath);
        }
        try {
            System.out.println(sleepTime);
            Thread.sleep(sleepTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        fileSet.setDir(file2);
        zip.setDestFile(zipfile);
        zip.setEncoding("gbk");//以gbk编码进行压缩,因为windows是默认以gbk编码压缩
        zip.addFileset(fileSet);
        zip.execute();
        FileUtils.deleteDirectory(file2);
        return zipFilePath;
    }
    public static void main(String[] args) throws IOException {
        String path="c:/test/1558320886535.txt";
        String path1="c:/test/15583208865591.pdf";
        List<String> list=new ArrayList<>();
        list.add(path);
        list.add(path1);
        compressFiles(list,"c:/test/"+TimeUtil.getCurDay()+"/"+UidUtil.getUid()+".zip");
    }


    //下载2
    public static void fileDown(DocobjectService docobjectService, String objId, DatabaselistService databaselistService, String filePath, HttpServletResponse response){
        try {
            Docobject objectid = docobjectService.findAllByObjectid(objId);
            String path = objectid.getServerfullpath();
//            String dbaname=categoryService.findByDbid(Integer.valueOf(objectid.getDbid())).getDba();
            Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(objectid.getDbid()));
            String dbaname=databaselist.getDbname();
            File file = new File(filePath+"/"+dbaname+"/"+path);
            String tempPath = filePath + "/tempFiles/"+dbaname+"/" +UidUtil.getUid()+"/"+ objectid.getObjectfilename();
            File tempfile = new File(tempPath);
            FileUtils.copyFile(file, tempfile);
            String filename = objectid.getObjectfilename();
            response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
            FileCopyUtils.copy(new FileInputStream(tempfile), response.getOutputStream());
        } catch (Exception e) {
            try {
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.print("<script type='text/javascript'>alert('文件资源异常,请联系管理员');history.go(-1)</script>");
                writer.flush();
                writer.close();
            } catch (Exception e1) {
                throw new YunExceptions(0, "下载单个文件的时候,资源异常");
            }
        }
    }
}
